const express = require('express');
const app = express()
const cors = require("cors")
var jwt = require('jsonwebtoken');



const { newEnforcer } = require('casbin');
const mysql = require('mysql2/promise');
const { BasicAdapter } = require('casbin-basic-adapter');



// app.use(cors())
app.use(express.static("./static"))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const router = require("./router");
const config = require('./config');
const connect = require('./model');

// 语法测试 
app.post("/test", async (req, res) => {


    res.json({
        code: 2000,
        data: []
    })
})


//  解析用户数据
var whilelsit = ["/login", "/register"]
app.use((req, res, next) => {
    if (whilelsit.includes(req.url)) {
        next()
        return
    }

    let token = req.headers.authorization
    jwt.verify(token, config.prived, function (err, decoded) {
        if (decoded) {
            // req 
            req.session = decoded
            next()
        } else {
            res.json({
                code: 40003,
                message: "用户身份过期,请重新登录"
            })
        }

    });

})


app.use(async (req, res, next) => {

    if (whilelsit.includes(req.url)) {
        next()
        return
    }

    const a = await BasicAdapter.newAdapter('mysql2',
        mysql.createConnection({
            host: 'localhost',
            user: 'root',
            database: 'taobao',
            password: "root123",
        }));

    const e = await newEnforcer('./rbac_model.conf', a);

    //  req.session  

    let sql = "select * from userinfo as a  left join role as b  on a.lv =b.id  where a.id = ? "
    let [userrole] = await connect.query(sql, [req.session.id])

    if (await e.enforce(userrole[0].role, req.url, req.method)) {
        console.log(userrole[0].role, req.url, req.method, "通过");
        next()
    } else {
        console.log(userrole[0].role, req.url, req.method, "不通过");
        res.json({
            code: 40005,
            message: "此角色暂无权限"
        })
    }
})


app.use(router)


app.listen(3300, () => {
})